import 'dart:async';
import 'dart:math';
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_app_minimizer_plus/flutter_app_minimizer_plus.dart';
import 'package:flutter_overlay_window/flutter_overlay_window.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:smart_translator/app/event/DataCallBack.dart';
import 'package:smart_translator/app/services/AudioService.dart';
import 'package:get/get.dart';
import 'package:smart_translator/app/utils/CommonUtil.dart';
import 'package:smart_translator/app/utils/tips.dart';
import '../../../const/AppConst.dart';
import '../../../db/DbDAOHelper.dart';
import '../../../nets/NetWorkManager.dart';
import '../../../routes/app_pages.dart';
import '../../../style/widget_style.dart';
import '../../../widgets/CommonWidgets.dart';


class ListenerTranslationController extends GetxController {
  var fontSize = 16.obs;
  var fontDisplay = '16(小)'.obs;

  final ScrollController fromController = ScrollController();

  final ScrollController fromControllerTopRegion = ScrollController();
  final ScrollController toControllerBottomRegion = ScrollController();

  AudioService audioService = Get.find<AudioService>();


  // 防抖计时器
  Timer? _debounceTimer;
  // 是否处于冷却状态
  bool isCoolingDown = false;

  String? taskId;

  //var showDoubleLanguages = false.obs;
  var listenerContentType = 0.obs; // 0 表示原文, 1表示译文, 2表示双语.

  // 50条声波纹.
  RxList<double> amplitudes = RxList.filled(50, 100.00);

  /*List.generate(
  widget.waveCount,
  (index) => Random().nextDouble() * 0.1
  )*/

  Timer? _audioWavetimer;



  @override
  void onInit() {
    super.onInit();
  }

  void initWsAndRecorder() {
    audioService.initAllState();
    audioService.connectedWsAndRecorder('wss://${NetWorkManager.WS_IP + NetWorkManager.SPEECH_RECOGNITION}?transStrategy=1', DataCallBack(
        confirmCallBack: (v) {

        },
        businessCallBack: (v) {
          scrollToBottom();
          scrollToBottomForTopRegion();
          scrollToBottomForBottomRegion();
        }
    ));
  }

  @override
  void onReady() {
    super.onReady();
    initWsAndRecorder();
  }

  @override
  void onClose() {
    saveTranslationRecords();
    audioService.stopRecorder();
    _debounceTimer?.cancel(); // 组件销毁时取消计时器
    if (_audioWavetimer != null) {
      _audioWavetimer?.cancel();
    }

    super.onClose();
  }

  void showPoupWindow(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (context) => SafeArea(child: Container(
          width: Get.width,
          height: 85.h,
          padding: EdgeInsets.all(15.h),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              InkWell(
                onTap: () {
                  Get.back();
                  showFontPoupWindow(context);
                },
                child: Container(
                  padding: EdgeInsets.only(top:8.h,bottom: 8.h,left: 35.w,right: 35.w),
                  decoration: BoxDecoration(
                    boxShadow: [
                      CommonWidgets.getBoxShadow(),
                    ],
                    color:  Colors.white,
                    borderRadius: BorderRadius.circular(8), // Optional: add border radius
                  ),
                  child: Column(
                    children: [
                      Text('${fontDisplay.value}',style: AppStyleThemeData.normal_bold_small,),
                      Text('字体大小',style: AppStyleThemeData.normal_bold_small,)
                    ],
                  ),
                ),
              ),
              SizedBox(width: 20.w,),
              Obx(()=> Container(
                child: InkWell(
                  onTap: () {
                    if (isCoolingDown) {
                        return;
                    };

                    isCoolingDown = true;

                    if (!audioService.isPlaying.value) {
                      audioService.record();
                    } else {
                      audioService.pauseRecorder();
                    }

                    _debounceTimer = Timer(Duration(milliseconds: 800), () {
                      isCoolingDown = false;
                    });


                  },
                  child: audioService.isPlaying.value ? Image.asset('assets/images/icon_play_realtime_btn_running.png',width: 55.w,height: 55.h):
                  Image.asset('assets/images/icon_play_realtime_btn.png',width: 55.w,height: 55.h),
                ),
              )),
              SizedBox(width: 20.w,),
              InkWell(
                onTap: () {
                  showLanguagePoupWindow(context);
                },
                child: Container(
                  padding: EdgeInsets.only(top:8.h,bottom:5.h,left: 31.w,right: 31.w),
                  decoration: BoxDecoration(
                    boxShadow: [
                      CommonWidgets.getBoxShadow(),
                    ],
                    color:  Colors.white,
                    borderRadius: BorderRadius.circular(8), // Optional: add border radius
                  ),
                  child: Column(
                    children: [
                      Obx(()=>Text('${audioService.fromLanFlagDisplay.value.substring(0,1) + '-' +  audioService.toLanFlagDisplay.value.substring(0,1)}',style: AppStyleThemeData.normal_bold_small,)),
                      Text('语言设置',style: AppStyleThemeData.normal_bold_small,)
                    ],
                  ),
                ),
              )
            ],
          ),
        )),
        backgroundColor: Colors.white.withValues(alpha: 0.5),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(
            top: Radius.zero, // 顶部直角
          ),
        ),
        barrierColor: Colors.black.withValues(alpha: 0.1)
    );
  }



  void playOrPause() {
    if (isCoolingDown) {
      return;
    };

    isCoolingDown = true;

    if (!audioService.isPlaying.value) {
      List<double> amps = [];
      _simulateAudioData();
      audioService.record(callback: DataCallBack(
        confirmCallBack: (amplitude) {

          /*amps.add(amplitude);
          if (amps.length == 50) {
              amplitudes.value.clear();
              amplitudes.value.addAll(amps);
              amps = [];
              print('listener controller1: ${amplitudes}');
              print('listener controller2: ${amps}');
          }*/

          /*if (amplitudes.length >= 50) {
            amplitudes.removeAt(0);
            amplitudes.add(amplitude);
          }*/


        }
      ));
    } else {
      stopSimulateAudioData();
      audioService.pauseRecorder();
    }

    _debounceTimer = Timer(Duration(milliseconds: 800), () {
      isCoolingDown = false;
    });
  }


  void _simulateAudioData() {
    _audioWavetimer = Timer.periodic(const Duration(milliseconds: 150), (timer) {
      // 生成随机振幅数据，模拟音频输入
      amplitudes.value = List.generate(50, (index) {
        // 生成0-15000之间的随机振幅（模拟16位PCM数据）
        return Random().nextDouble() * (15000 - 5000) + 5000;
      });

   });
  }

  void stopSimulateAudioData() {
    amplitudes.value = [];
    _audioWavetimer?.cancel();
  }


  void showFontPoupWindow(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (context) => SafeArea(child: Container(
          padding: EdgeInsets.all(15.h),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('字体大小', style: AppStyleThemeData.HINT_TEXT_STYLE_small,),
                  InkWell(
                    onTap: () {
                      Get.back();
                    },
                    child: Image.asset('assets/images/icon_poup_window_close.png',width: 10.w,height: 10.h),
                  )

                ],
              ),
              SizedBox(height: 15.h,),
              CommonWidgets.getMyDivider(),
              SizedBox(height: 15.h,),
              InkWell(
                onTap: () {
                  fontSize.value = 32;
                  fontDisplay.value = '32 (偏大)';
                  Get.back();
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text('32 (偏大)',style: fontSize.value == 32 ? AppStyleThemeData.linkStyle_BIG: TextStyle(
                        color: Colors.black,
                        fontSize: 16.sp
                    )),
                  ],
                ),
              ),
              SizedBox(height: 15.h,),
              CommonWidgets.getMyDivider(),
              SizedBox(height: 15.h,),
              InkWell(
                onTap: () {
                  fontSize.value = 24;
                  fontDisplay.value = '24 (大)';
                  Get.back();
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text('24 (大)',style:  fontSize.value == 24 ? AppStyleThemeData.linkStyle_BIG: TextStyle(
                        color: Colors.black,
                        fontSize: 16.sp
                    ),),
                  ],
                ),
              ),
              SizedBox(height: 15.h,),
              CommonWidgets.getMyDivider(),
              SizedBox(height: 15.h,),
              InkWell(
                onTap: () {
                  fontSize.value = 18;
                  fontDisplay.value = '18 (适中)';
                  Get.back();
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text('18 (适中)',style:  fontSize.value == 18 ? AppStyleThemeData.linkStyle_BIG: TextStyle(
                        color: Colors.black,
                        fontSize: 16.sp
                    ),),
                  ],
                ),
              ),
              SizedBox(height: 15.h,),
              CommonWidgets.getMyDivider(),
              SizedBox(height: 15.h,),
              InkWell(
                onTap: () {
                  fontSize.value = 16;
                  fontDisplay.value = '16 (小)';
                  Get.back();
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text('16 (小)',style:  fontSize.value == 16 ? AppStyleThemeData.linkStyle_BIG: TextStyle(
                        color: Colors.black,
                        fontSize: 16.sp
                    )),
                  ],
                ),
              ),
            ],
          ),
        )),
        backgroundColor: Colors.white
    );
  }


  void showLanguagePoupWindow(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (context) => SafeArea(child: Container(
          padding: EdgeInsets.all(15.h),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('语言设置', style: AppStyleThemeData.HINT_TEXT_STYLE_small,),
                  InkWell(
                    onTap: () {
                      Get.back();
                    },
                    child: Image.asset('assets/images/icon_poup_window_close.png',width: 10.w,height: 10.h),
                  )

                ],
              ),
              SizedBox(height: 15.h,),
              CommonWidgets.getMyDivider(),
              SizedBox(height: 15.h,),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  InkWell(
                    onTap: () {
                      chooseFromLanguages();
                    },
                    child: Container(
                      width: 135.w,
                      height: 48.h,
                      padding: EdgeInsets.all(8.w),
                      decoration: BoxDecoration(
                        boxShadow: [
                          CommonWidgets.getBoxShadow(),
                        ],
                        color:Colors.white,
                        borderRadius: BorderRadius.circular(8), // Optional: add border radius
                      ),
                      child: Obx(()=>Center(
                        child: Text('${audioService.fromLanFlagDisplay.value}',style: AppStyleThemeData.normal_bold,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      )),
                    ),
                  ),

                  Container(
                    padding: EdgeInsets.all(14.w),
                    height: 48.h,
                    decoration: BoxDecoration(
                      boxShadow: [
                        CommonWidgets.getBoxShadow(),
                      ],
                      color:Colors.white,
                      borderRadius: BorderRadius.circular(8), // Optional: add border radius
                    ),
                    child: Image.asset('assets/images/icon_index_lang_exchange.png',width: 20.w,height: 20.h,),
                  ),
                  InkWell(
                    onTap: () {
                      chooseToLanguages();
                    },
                    child: Container(
                      width: 135.w,
                      height: 48.h,
                      padding: EdgeInsets.all(8.w),
                      decoration: BoxDecoration(
                        boxShadow: [
                          CommonWidgets.getBoxShadow(),
                        ],
                        color:Colors.white,
                        borderRadius: BorderRadius.circular(8), // Optional: add border radius
                      ),
                      child: Obx(()=>Center(
                        child: Text('${audioService.toLanFlagDisplay.value}',style: AppStyleThemeData.normal_bold,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      )),
                    ),
                  )
                ],
              ),
              SizedBox(height: 15.h,),
              Container(
                width: Get.width,
                child: ElevatedButton(onPressed: () {

                  changeLanguageReInitial();

                  Get.back();
                }, child: Text('确定')),
              ),
            ],
          ),
        )),
        backgroundColor: Colors.white
    );
  }

  void saveTranslationRecords() {
    if (audioService.finalFromLanguage.value.trim() != '' && audioService.finalToLanguage.value.trim() != '') {
      DbDAOHelper().saveTranslateHistory(audioService.fromLanguage, audioService.toLanguage,
          audioService.finalFromLanguage.value, audioService.finalToLanguage.value, audioService.taskId ?? '01010101010101',AppConst.TRANSLATOIN_TYPE_LISTENING,
      audioService.fromLanFlagDisplay.value,audioService.toLanFlagDisplay.value);
    }

  }


  void showFloatingWindow (BuildContext context) async {
    if(!audioService.isPlaying.value) {
      Tips.showToast('请先开始录音.');
      return;
    }

    bool status = await FlutterOverlayWindow.isPermissionGranted();
    if (!status) {
      bool? result = await FlutterOverlayWindow.requestPermission();
      if (result!) {
        Tips.showToast('已经获取到权限');
      } else {
        Tips.showToast('未获取到授权.');
        return;
      }
    }

    FlutterOverlayWindow.isActive().then((show) async {
       if(show) {
         await FlutterOverlayWindow.closeOverlay();
       } else {
         await FlutterOverlayWindow.showOverlay(
           flag: OverlayFlag.defaultFlag,
           visibility: NotificationVisibility.visibilityPublic,
           width: (CommonUtil.getScreenSize_ofWidth(context)*0.95).toInt(),
           height: (MediaQuery.of(context).size.height * 0.7).toInt(),
           startPosition: const OverlayPosition(0, -259),
           overlayTitle: "SmartTranslator",
           overlayContent: '浮窗运行中',
           positionGravity: PositionGravity.left,
           enableDrag: true,
         );
         FlutterAppMinimizerPlus.minimizeApp();

       }
    });



  }


  void scrollToBottom() {
    if (fromController.hasClients) {
      Future.delayed(Duration(milliseconds: 500),() {
        fromController.animateTo(
          fromController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      });
    }
  }

  void scrollToBottomForTopRegion () {
    if (fromControllerTopRegion.hasClients) {
      Future.delayed(Duration(milliseconds: 500),() {
        fromControllerTopRegion.animateTo(
          fromControllerTopRegion.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300 ),
          curve: Curves.easeOut,
        );
      });
    }
  }

  void scrollToBottomForBottomRegion () {
    if (toControllerBottomRegion.hasClients) {
      Future.delayed(Duration(milliseconds: 500),() {
        toControllerBottomRegion.animateTo(
          toControllerBottomRegion.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      });
    }
  }


  void chooseFromLanguages() async {
    final languageItem = await Get.toNamed(Routes.LANGUAGE_OPINION,parameters: {
      'code': audioService.fromLanguage
    });
    audioService.fromLanguage = languageItem['code'];
    audioService.fromLanFlagDisplay.value = languageItem['desc'];

  }

  void chooseToLanguages() async {
    final languageItem = await Get.toNamed(Routes.LANGUAGE_OPINION,parameters: {
      'code': audioService.toLanguage
    });
    audioService.toLanguage = languageItem['code'];
    audioService.toLanFlagDisplay.value = languageItem['desc'];

  }

  void changeLanguageReInitial() {
    if (audioService.isPlaying.value) {
      audioService.pauseRecorder();
    }

    audioService.reInitWs();
    audioService.connectedWsAndRecorder('wss://${NetWorkManager.WS_IP + NetWorkManager.SPEECH_RECOGNITION}?channel=azure&transStrategy=2', DataCallBack(
        confirmCallBack: (v) {
          audioService.record();
        }
    ));
  }

  void showDoubleLanguage() {
      // showDoubleLanguages.value = !showDoubleLanguages.value;
    if (listenerContentType.value == 0) {
      listenerContentType.value = 1;
    } else if (listenerContentType.value == 1) {
      listenerContentType.value = 2;
    } else {
      listenerContentType.value = 0;
    }
  }

  void showAudioLogsPoupWindow(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (context) => SafeArea(child: Container(
          padding: EdgeInsets.all(15.h),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Obx(()=> Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Wrap(children: [
                     Text('Recording: ${audioService.showLogText.value}')
                  ]),
                ],
              ))
            ],
          ),
        )),
        backgroundColor: Colors.white
    );
  }

  void quite() {
     if (audioService.isPlaying.value) {
       CommonWidgets.showConfirmDialog(Get.context!, '提示', '返回后将关闭并退出听译翻译', '退出', '悬浮窗显示', DataCallBack(
           confirmCallBack: (v) {
             Get.back(); //退出听译.
           },
           cancleCallBack: (v) {
              FlutterOverlayWindow.isActive().then((show) async {
                  if (show) {
                    FlutterAppMinimizerPlus.minimizeApp();
                  } else {
                    showFloatingWindow(Get.context!);
                  }
              });
           }
       ));
     } else {
       Get.back();
     }
  }

}
